vimfandomcom-20200223-history
Easier buffer switching
One of the keys to effective Vim usage is effective buffer management. Vim doesn't force you to click on a tab every time you want to look at another file, but if you don't know how to easily find the buffer you want, it can be just as frustrating. Terminology Some of the terms used in this tip are briefly explained below. For more details see the buffer FAQ and . *When a file is loaded into memory for editing, a new buffer is created to hold it. *A buffer can be created to hold text that isn't related to a file, such as a directory listing. *A window is a view port onto a buffer. *A buffer is active if it is shown in a window. *A buffer is hidden if it is not shown in a window. *A buffer is a listed buffer if it is always shown in the buffer list. *A buffer is an unlisted buffer if it is not shown in the buffer list by default. *Each buffer is given a unique number when it is first created. It keeps this number for the duration of the Vim session. *The name of a buffer is the name of the file that has been loaded into it, or for buffers not containing the contents of a file, it can be any string. Listing buffers The :buffers command lists the current buffers. There are two alternate names for this command :ls and :files. By default, only listed buffers will be displayed. Unlisted buffers can be included by appending !, for example :ls!. Switching to another buffer The command to switch to another buffer is :buffer, which is often abbreviated as :b, :bu or :buf. :buffer can be given either the name or the number of the buffer to edit. Switching by name When using the buffer name as the argument to :buffer, you don't have to specify the entire name. However, if more than one buffer matches the given argument then the buffers won't be switched. Any fragment of the buffer name can be used to match against, although buffers which match at the beginning of their name will be selected in preference to buffers which match elsewhere in their name. For example, if you have the buffers request_manager.java and queue_manager.java then :buffer que matches both of them, but will switch to queue_manager.java as it matches at the beginning. Tab completion can be used to complete the buffer name, :buffer any snippet of text will complete to the full buffer name if only one buffer matches any snippet of text. If more than one buffer matches, the matches will be cycled through on further presses of . The switch will take place once is entered with a unique buffer name. Again, any fragment of the buffer name can be used to complete the matching buffer, for example, request_manager.java can be completed using t_ma or req or r.java. Instead of , you can press Ctrl-D to list all matching names. If you would prefer to be able to select the buffer from the list of partial matches the following function can be used. It will jump to the matching buffer if only one match is found, or if there are many matches it will print a list of the matching buffers in the command-line area, and allow you to select one of the matching buffers by buffer number. function! BufSel(pattern) let bufcount = bufnr("$") let currbufnr = 1 let nummatches = 0 let firstmatchingbufnr = 0 while currbufnr <= bufcount if(bufexists(currbufnr)) let currbufname = bufname(currbufnr) if(match(currbufname, a:pattern) > -1) echo currbufnr . ": ". bufname(currbufnr) let nummatches += 1 let firstmatchingbufnr = currbufnr endif endif let currbufnr = currbufnr + 1 endwhile if(nummatches 1) execute ":buffer ". firstmatchingbufnr elseif(nummatches > 1) let desiredbufnr = input("Enter buffer number: ") if(strlen(desiredbufnr) != 0) execute ":buffer ". desiredbufnr endif else echo "No matching buffers" endif endfunction "Bind the BufSel() function to a user-command command! -nargs=1 Bs :call BufSel("") Switching by number If you know the number of the buffer you want to switch to, you can pass that as the argument to :buffer, for example :buffer 5 will switch to buffer number 5. An alternative which can be used from normal mode is buffer number, for example 5 will switch to buffer number 5. When there are several buffers open in a Vim session, it can become difficult to keep track of the buffers and their respective buffer numbers. If this is the case, switching to a different file can be made easier using a simple map: :nnoremap :buffers:buffer When F5 is pressed, a numbered list of file names is printed, and the user needs to type a single number based on the "menu" and press enter. The "menu" disappears after choosing the number so it appears only when you need it. The at the end of the map isn't required, but does help to separate the input from the "prompt". As the :buffer command is being used to perform the switch, the buffer name could be used instead, if preferred. The :edit command can also be used to switch to a given buffer number if the argument begins with #. For example, :edit #5 will switch to buffer number 5. This can be used in the above map to allow the user to view the current buffers and then either enter the number you wish to switch to, or if it isn't yet loaded, delete the # and enter the path to the file. Switching to the previously edited buffer Often the buffer that you want to edit is the buffer that you have just left. Vim provides a couple of convenient commands to switch back to the previous buffer. These are (or ) and :b#. Both of these technically edit the alternate file, although this is usually the previously edited buffer. Leaving modified buffers If Vim is running with its default settings, or in vi compatible mode, the :buffer command will not abandon the buffer until any changes have been written. There are a few ways this can be changed: *Append ! to the command to force the current buffer to be hidden, despite being modified. For example, if buffer 1 is the current buffer and it has been modified, the command :buffer! 2 (or :b! 2) would hide buffer 1 (keeping its changes), and display buffer 2. *Set the hidden option (:set hidden) so any buffer can be hidden (keeping its changes) without first writing the buffer to a file. This affects all commands and all buffers. *Set the confirm option (:set confirm) so that when you tell Vim to abandon a buffer but you have unsaved changes, Vim will ask you whether to save your changes first, abandon them, or cancel the action. The choices given do not seem to allow simply hiding the buffer as in the previous options. *Set either the autowrite or the autowriteall options (:set autowrite or :set autowriteall) to automatically save any changes made to the buffer before it is hidden. Conveniently accessing buffers Built-in features In gvim, you can use the Buffers menu to conveniently access buffers (tear off the menu to make an always-visible list). Or, put the following in your vimrc: set wildchar= wildmenu wildmode=full Now, pressing Tab on the command line will show a menu to complete buffer and file names. If you include the following, you can also press F10 to open the buffer menu. set wildcharm= nnoremap :b Try this example to see how powerful the wildmenu is. :args vehicle.c vehicle.h car.c car.h jet.c jet.h jetcar.c jetcar.h :b " offers all buffers in a menu :b car " offers car.c car.h :b *car " offers car.c jetcar.c car.h jetcar.h :b .h " offers the *.h buffers :b .c " offers the *.c buffers :b ar.c " offers car.c jetcar.c :b j*c " offers jet.c jetcar.c jetcar.h Plugins You may want to install the script, and place the following in your vimrc. Pressing Alt-F12 opens a window listing the buffers, and you can press Enter on a buffer name to go to that buffer. Or, press F12 (next) or Shift-F12 (previous) to cycle through the buffers. " Buffers - explore/next/previous: Alt-F12, F12, Shift-F12. nnoremap :BufExplorer nnoremap :bn nnoremap :bp Mappings for buffer number If you know the buffer numbers, the following mappings are useful. For example, typing \1 (assuming the default backslash leader) will switch to buffer number 1. " Mappings to access buffers (don't use "\p" because a " delay before pressing "p" would accidentally paste). " \l : list buffers " \b \f \g : go back/forward/last-used " \1 \2 \3 : go to buffer 1/2/3 etc nnoremap l :ls nnoremap b :bp nnoremap f :bn nnoremap g :e# nnoremap 1 :1b nnoremap 2 :2b nnoremap 3 :3b nnoremap 4 :4b nnoremap 5 :5b nnoremap 6 :6b nnoremap 7 :7b nnoremap 8 :8b nnoremap 9 :9b nnoremap 0 :10b " It's useful to show the buffer number in the status line. set laststatus=2 statusline=%02n:%<%f\ %h%m%r%=%-14.(%l,%c%V%)\ %P The following lets you type N''gb to jump to buffer number ''N (a number from 1 to 99). For example, typing 12gb would jump to buffer 12. let c = 1 while c <= 99 execute "nnoremap " . c . "gb :" . c . "b\" let c += 1 endwhile Scripts Some scripts for buffer switching are listed below, in order by the script id. You can search Vim Scripts for "buffer" to find others. * A popular buffer explorer. * A fast and extensible buffer explorer. * Another buffer select script * To select a buffer from a PopUp menu. * A popular and compact buffer explorer. Clickable tabs w/ `set mouse=a` * * * Switch buffers using an incremental search. * More balanced buffers menu hierarchy. * Buffer browser. * A 1-file buffer list plugin with grouping. * Simple, fast, and slick non-disturbing buffer list. * * Automatically maps buffers to function keys. * Minimalistic buffer tabs saving screen space. * Switch buffer with Alt-. * A quick buffer selector/switcher. * Dynamic filesystem and buffer explorer. * Very small but quick and powerful buffer manager. * Explore buffer/file/MRU/favorite with a fuzzy pattern. * Switch very quickly between active buffers. * Conveniently navigate buffers; incremental search by name. * Quickly switch to most recently used buffer. * Commands: VxBufListSelect/VxOpenRecentFile/VxFileBrowser, with filtering and MRU * Fast buffer and file navigation * Quickly navigate between buffers using an incremental search by name (a combination of and ) * Lists buffers in a new split, and quickly go to selected buffer in previous window, new (vertical/horizontal) split, or new tab page. Walk up and down buffer list, previewing buffers quickly without leaving buffer list. * A fast, easy to use buffer list plugin for switching and managing buffers.buffer list contains tab and window numbers.Provides commands to load, delete, switch,horizontal/vertical/diff split open buffers and command to close opened windows. * Unite.vim script for fast navigation between mru, buffers, files in project tree, user-defined menus and many more See also *Cycle through buffers including hidden buffers to cycle through existing buffers, in order by buffer number References *Vim buffer FAQ * * * * * * Comments I suggest changing all mappings starting with , to start with instead. I know that this is more confusing, but I strongly dislike seeing a perfectly good command — that is , — go to waste before the user has had a chance to learn it. I think this should be done for all articles. (Spiiph 22:19, September 4, 2009 (UTC)) :Good idea. I changed this tip. I have left a few ',' mappings in the past for simplicity, but consistenly using would be better. JohnBeckett 09:52, September 5, 2009 (UTC) The following simple user-defined command :Buffer allows switching a buffer in the current window choosing it from the buffer list: command -nargs=? -bang Buffer if != '' | exe 'buffer '. | else | ls | let buffer_nn=input('Which one: ') | if buffer_nn != '' | exe buffer_nn != 0 ? 'buffer '.buffer_nn : 'enew' | endif | endif It can be abbreviated as :B It shows the buffer list printed out by the :ls command and asks a user for the input which is transferred to :buffer command. The command with an exclamation mark :B! executes :ls! which includes unlisted buffers in the list. Entering a zero as answer creates a new buffer with :enew command. Also a desired buffer number or part of buffer's name can be specified directly as argument to :B . (Gmikeus 19:43, December 19, 2010 (UTC))